-module(app_rewrite).
-include("yaws_api.hrl").
-include("rec_dec.hrl").
-export([arg_rewrite/1]).

arg_rewrite(Arg) ->
	BizCookie = "bizcookie",
	H = Arg#arg.headers,
	case get_cookie_val(BizCookie, H) of
	{error,login_require} ->
		do_rewrite(Arg);
%%		user_adapter:auth(operator,yaws_api:parse_query(Arg)),
%%		Arg;
	{ok, Session} ->
		io:format("get cookie:~p~n",[Session]),
		Arg#arg{opaque=Session};
	{error,Op} ->
		io:format("error in cookie ~p~n",[Op]),
		do_rewrite(Arg)
	end.
	
get_cookie_val(C,H) ->
	case yaws_api:find_cookie_val(C,H#headers.cookie) of
	[] ->
		%% login required
		{error,login_require};
	Cookie ->
		yaws_api:cookieval_to_opaque(Cookie)
	end.
login_pages() ->
	["login_control.yaws"].
	
	
do_rewrite(Arg) ->
	Req = Arg#arg.req,
	{abs_path, Path} = Req#http_request.path,
	case by_pass(Path) of
	false ->
		[SN|Others] = string:tokens(Path,"/"),
		case vendor_service:get({short_name,SN}) of
		[] ->
			Arg#arg{req = Req#http_request{path = {abs_path, "/www/login.html"}},state = {abs_path, Path}};
		[Vendor] ->
			io:format("add vendor info~n"),
			Arg#arg{req = Req#http_request{path = {abs_path,string:concat("/www/login.html?vendor_id=",binary_to_list(Vendor#vendor_rec.id))}},state = {abs_path, Path}}
		end;
	true ->
		Arg
	end.

by_pass(Path) ->
	Patterns = ["login_control.yaws","/js","/css","images","/mobile/login.html","logout.yaws","register.yaws",
				"unauth_act.yaws","register_simple.yaws","register_mgr.yaws","static"],
	by_pass(Path,Patterns).
by_pass(_,[]) ->
	false;
by_pass(Path,[Pattern|Patterns]) ->
	case string:str(Path,Pattern) of
	0 ->
		by_pass(Path,Patterns);
	_ ->
		true
	end.